package com.wan.filter;

import com.alibaba.fastjson.JSON;
import com.wan.common.BaseContext;
import com.wan.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    // 用于处理路径匹配
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 1.获取请求的URI
        String requestURI = request.getRequestURI();

        // 获取每次请求过来的路径
        log.info("拦截到请求：{}",requestURI);

        // 定义不需要拦截的请求
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login"
        };
        // 2.判断本次请求需不需要处理
        boolean check = check(urls, requestURI);
        // 3.进入if判断表示不需要处理
        if (check){
            // 放行代码
            filterChain.doFilter(request,response);
            return;
        }
//        4-1. 判断登录状态如果已登录，则直接放行
        Long empId = (Long) request.getSession().getAttribute("employee");
        BaseContext.setCurrentId(empId);
        if (empId != null){
            filterChain.doFilter(request,response);
            return;
        }

        //4-2. 判断登录状态如果已登录，则直接放行
        Long userId = (Long) request.getSession().getAttribute("user");
        BaseContext.setCurrentId(userId);
        if (userId != null){
            filterChain.doFilter(request,response);
            return;
        }

        // 5. 如果未登录就返回到登录页面，使用输出流的方式向客户端来响应数据 NOTLOGIN这个是前端固定要求的写法
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 遍历当前请求的路径是否包含在urls数组中 来决定当前请求是否放行
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            // 判断是否为true如果是true就直接返回可以放行
            if (match){
                return true;
            }
        }
        // 如果没有匹配到就返回false
        return false;
    }
}
